import { Card, Form, Input, Button, message } from "antd";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import type { AppDispatch } from "@/store";
import { fetchLogin } from "@/store/modules/userStore";
import StyledLogin from "./index.css";
import logo from "@/assets/logo.png";

const Login = () => {
  const dispatch: AppDispatch = useDispatch()
  const navigate = useNavigate()
  // antd表单的验证规则
  const mobileRules = useMemo(() => {
    return [
      // 串行校验逻辑
      { required: true, message: '请输入手机号' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '手机号码格式不对'
      }
    ]
  }, []);
  const codeRules = useMemo(() => {
    return [
      { required: true, message: '请输入验证码' },
    ]
  }, []);

  // 点击表单按钮后通过验证的回调
  const [loginButtonDisAbled, setLoginButtonDisAbled] = useState(false)
  const onFinish = useCallback(
    async (loginForm: { mobile: string, code: string }) => {
      setLoginButtonDisAbled(true);
      try{
        await dispatch(fetchLogin(loginForm)); 
        navigate('/')
        message.success('登录成功')  
      }catch(e){
        message.error('登录不成功，请重新尝试')
      }
      setLoginButtonDisAbled(false);
    }, [dispatch, navigate]
  ) 

  return (
    <StyledLogin>
      <div className="login">
        <Card className="login-container">
          <img className="login-logo" src={logo} alt="jike-login" />
          {/* 登录表单 */}
          <Form validateTrigger={['onBlur']} onFinish={onFinish}>
            <Form.Item name="mobile" rules={mobileRules}>
              <Input size="large" placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item name="code" rules={codeRules}>
              <Input size="large" placeholder="请输入验证码" maxLength={6}/>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" size="large" block disabled={loginButtonDisAbled}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </StyledLogin>
  );
};

export default Login;
